<?php
/**
 * 当指定的商品购买数量,在首批数量内进行打折
 * $ 2017-11-07 	add by hzk
 *  限制数量
 */
class b2c_promotion_solutions_fdtopercent implements b2c_interface_promotion_solution
{

//当指定的商品购买数量,在首批数量内进行打折
    public $name = "以固定折扣出售【首批打折】【商品促销】"; // 名称
    public $first_nums= "首批促销数量为"; // 首批促销数量//////////add
    public $type = array('prefilter','cart'); // 应用范围 目前只有[预过滤(prefilter),购物车(cart)]
    public $desc_pre = '价格乘以';
    public $desc_post = '%折扣出售';
    private $description = '';
    public $desc_tag= '打折';

    //同种方案在同一商品上 适用 排他原则
    public $stop_rule_with_same_solution = true;



    public function __construct( $app ) {
        $this->app = $app;
        $this->name = app::get('b2c')->_($this->name);
        $this->desc_pre = app::get('b2c')->_($this->desc_pre);
        $this->desc_post = app::get('b2c')->_($this->desc_post);
    }



    /**
     * 优惠方案模板
     * @param array $aConfig // 设置信息(修改的时候传入)
     * @return string // 返回要输出的模板html
     */
    public function config($aData = array()) {
        return <<<EOF
		{$this->first_nums}<input name="action_solution[b2c_promotion_solutions_fdtopercent][nums]" vtype='required&&unsigned' value="{$aData['nums']}" />
{$this->desc_pre}<input name="action_solution[b2c_promotion_solutions_fdtopercent][percent]" vtype='required&&unsigned' value="{$aData['percent']}" />{$this->desc_post}
EOF;
    }

    /**
     * 优惠方案应用
     *
     * @param array $object  // 引用的一个商品信息
     * @param array $aConfig // 优惠的设置
     * @param array $cart_object // 购物车信息(预过滤的时候这个为null)
     * @return void // 引用处理了,没有返回值
     */
    public function apply(&$object,$aConfig,&$cart_object = null) {//从b2c_cart_prefilter_promotion_goods文件的_action方法中加入传入参数 促销id、活动开始时间、活动结束时间
		// $aConfig['rule_id']  	//加入促销id方便筛选 
		// $aConfig['from_time'] 	//加入活动开始时间方便筛选 
		// $aConfig['to_time'] //加入活动结束时间方便筛选  
		
        $omath = kernel::single('ectools_math');
        $rule_nums = max(0, $aConfig['nums']);//首批数量
        $rulePercent = max(0, $aConfig['percent']);
        $rulePercent = min($rulePercent, 100);


		
		$member_id = kernel::single('b2c_user_object')->get_member_id();
        $db_order = app::get('b2c')->model('orders'); 
        $db_order_goods = app::get('b2c')->model('order_items');
        $gift_type = app::get('b2c')->_('product');
        $temp_goods_id = $object['obj_items']['products'][0]['goods_id'];
 
        $fromtime = $aConfig['from_time'];
        $totime = $aConfig['to_time'];
 
		$sql = "SELECT * FROM sdb_b2c_order_items AS a LEFT JOIN sdb_b2c_orders AS b ON a.order_id=b.order_id WHERE b.member_id = {$member_id}   AND b.createtime>{$fromtime}  AND b.createtime<{$totime} AND a.item_type = 'product' AND a.goods_id ={$temp_goods_id} ";
				 
		$str = kernel::database()->select($sql); 
		$order_goods_nums = 0; 
		foreach ($str as $one_order) {
			 $order_goods_nums += (int)$one_order['nums'];//总计订单中该商品的个数 
		}	
		$can_discount_nums = $rule_nums - $order_goods_nums; //该商品剩余可使用首批打折的个数
		$productQuantity = $object['obj_items']['products'][0]['quantity'];
        $goodsQuantity = $object['quantity'];

			
		////////首批个数限制
        $qty = $productQuantity*$goodsQuantity;	 
		if(($can_discount_nums>0)&&($can_discount_nums>$qty)){
			$qty = $qty;
		}
		if(($can_discount_nums>0)&&($can_discount_nums<$qty)){
			$qty = $can_discount_nums;
		}
		if($can_discount_nums<=0){
			$qty = 0 ;
		} 
 
			
		$productPrice = $object['obj_items']['products'][0]['price']['buy_price'];
        $discountAmount = $omath->number_multiple(
                                                  array(
															$omath->number_multiple(array($qty,$productPrice)),
                                                            (1 - $rulePercent/100)
                                                        )
                                                    );
        $object['discount_amount_order'] = $omath->number_plus( array($object['discount_amount_order'],$discountAmount) );
   
		
        $this->setString($aConfig);  
		$data['can_discount_nums'] =  $can_discount_nums;
		$data['qty'] =  $qty;
		$data['object'] =  $object;
		$data['aConfig'] =  $aConfig;
		$data['cart_object'] =  $cart_object;
		file_put_contents("0000000000_apply_data.txt", var_export($data, 1).PHP_EOL, FILE_APPEND);
 		###################################
    }



    /**
     * 优惠方案应用
     *
     * @param array $object  // 引用的一个商品信息
     * @param array $aConfig // 优惠的设置
     * @param array $cart_object // 购物车信息(预过滤的时候这个为null)
     * @return void // 引用处理了,没有返回值
     */
    public function apply_order(&$object, &$aConfig,&$cart_object = null) {
  
        if(is_null($cart_object)) return false;
        $omath = kernel::single('ectools_math');

        $rulePercent = max(0, $aConfig['percent']);
        $rulePercent = min($rulePercent, 100);
 
        $object['discount_amount_order'] += $omath->number_multiple(
                                                                array(
                                                                    ($cart_object['subtotal'] - $cart_object['discount_amount_prefilter']),
                                                                    (1 - $rulePercent/100)
                                                                )
                                                            );

        $this->desc_pre = app::get('b2c')->_('订单总价格乘以');
        $this->setString($aConfig);
		
 		$data2['object'] =  $object;
		$data2['aConfig'] =  $aConfig;
		$data2['cart_object'] =  $cart_object;
		file_put_contents("0000000000_apply_order_data.txt", var_export($data2, 1).PHP_EOL, FILE_APPEND);
    }






    public function setString($aData) {
        $this->description = $this->first_nums . $aData['nums'] . $this->desc_pre . $aData['percent'] . $this->desc_post;
    }

    public function getString() {
        return $this->description;
    }



    public function get_status() {
        return true;
    }
	/*判断是否在订单或者商品的  优惠方案 中显示
	 *在订单和商品优惠方案都显示=====》》》》》则在文件不需要此方法
	 *return false :不在订单优惠方案显示
	 *return true  :在订单优惠方案显示
	 */
    public function is_order_solution() {
        return false;
    }

    /**
	 * 校验参数是否正确
	 * @param mixed 需要校验的参数
	 * @param string error message
	 * @return boolean 是否成功
	 */
	public function verify_form($data=array(), &$msg='')
	{
		if (!$data) return true;

		/** 订单够满金额 **/
		if (!isset($data['action_solution']['b2c_promotion_solutions_fdtopercent']['percent']) || !$data['action_solution']['b2c_promotion_solutions_fdtopercent']['percent'])
		{
			$msg = app::get('b2c')->_('请指定订单固定折扣的金额！');
			return false;
		}

		if (!is_numeric($data['action_solution']['b2c_promotion_solutions_fdtopercent']['percent']) || $data['action_solution']['b2c_promotion_solutions_fdtopercent']['percent'] < 0 || $data['action_solution']['b2c_promotion_solutions_fdtopercent']['percent'] > 100)
		{
			$msg = app::get('b2c')->_('固定折扣必须是在0-100的数字！');
			return false;
		}
		// if(floor($a)==$a){
		// if(!is_int($data['action_solution']['b2c_promotion_solutions_fdtopercent']['nums'])){
		if(!(floor($data['action_solution']['b2c_promotion_solutions_fdtopercent']['nums'])==$data['action_solution']['b2c_promotion_solutions_fdtopercent']['nums'])){
			$msg = app::get('b2c')->_('首批打折数量必须是整数！');
			// $msg = (!true||false );
			return false;
		} 
		
		if ($data['action_solution']['b2c_promotion_solutions_fdtopercent']['nums'] < 0 )
		{
			$msg = app::get('b2c')->_('首批打折数量必须是  不小于0  的整数！');
			// $msg = (!true||false );
			return false;
		}
		/** end **/

		return true;
	}

    function get_desc_tag(){
        if(isset($this->cart_display)){
            $desc_tag['display'] = $this->cart_display;
        }else{
            $desc_tag['display'] = true;
        }
        $desc_tag['name'] = $this->desc_tag;
        return $desc_tag;
    }

}
